package org.je.image;

import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

/**
 * @author fanyifeng
 */
public class ImageUtil
{
	/**
	 * 0 : default, 1 : opaque, 2 : bitmask, 3: translucent
	 * 
	 * @param w
	 * @param h
	 * @param tpy
	 * @return img
	 */
	public static BufferedImage createCompatibleImage(int w, int h, int tpy) {
		if (tpy < 0 || tpy > 3) {
			throw new RuntimeException("transparency-code-error: must >=0 and <=3");
		}
		return tpy == 0 ? getGraphicsConfiguration().createCompatibleImage(w ,h) : getGraphicsConfiguration()
				.createCompatibleImage(w ,h ,tpy);
	}

	/**
	 * 0 : default, 1 : opaque, 2 : bitmask, 3: translucent
	 * 
	 * @param img
	 * @param tpy
	 * @return compatible image
	 */
	public static BufferedImage toCompatibleImage(BufferedImage img, int tpy) {
		if (tpy < 0 || tpy > 3) {
			throw new RuntimeException("transparency-code-error: must >=0 and <=3");
		}
		BufferedImage dest = createCompatibleImage(img.getWidth() ,img.getHeight() ,tpy);
		copy(img ,dest);
		return dest;
	}

	/**
	 * @param src
	 * @param dest
	 */
	public static void copy(BufferedImage src, BufferedImage dest) {
		int w = src.getWidth();
		int h = src.getHeight();
		if (w != dest.getWidth() || h != dest.getHeight()) {
			throw new RuntimeException("copey-image-error: size-not-match!");
		}
		for (int y = 0; y < h; ++y) {
			for (int x = 0; x < w; ++x) {
				dest.setRGB(x ,y ,src.getRGB(x ,y));
			}
		}
	}

	/**
	 * @param file
	 * @return bufferedImage
	 */
	public static BufferedImage loadOriginalImage(File file) {
		try {
			return ImageIO.read(file);
		} catch (IOException ex) {
			throw new RuntimeException("read image[" + (file == null ? "null" : file.getPath()) + "] error",ex);
		}
	}

	public static GraphicsConfiguration getGraphicsConfiguration() {
		return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
	}
}
